import 'dart:math';
import 'package:flutter/material.dart';
import 'morse_translator.dart';

/// 测验难度
enum QuizDifficulty {
  easy,   // 10题
  medium, // 20题
  hard,   // 30题
}

/// 摩尔斯电码测验页面
class MorseQuizPage extends StatefulWidget {
  final String category;
  final QuizDifficulty difficulty;

  const MorseQuizPage({
    super.key,
    required this.category,
    required this.difficulty,
  });

  @override
  State<MorseQuizPage> createState() => _MorseQuizPageState();
}

class _MorseQuizPageState extends State<MorseQuizPage> {
  late List<QuizQuestion> _questions;
  int _currentQuestionIndex = 0;
  int _score = 0;
  bool _hasAnswered = false;
  String? _selectedAnswer;
  bool _isQuizCompleted = false;
  
  final Random _random = Random();

  @override
  void initState() {
    super.initState();
    _generateQuestions();
  }

  int get _totalQuestions {
    switch (widget.difficulty) {
      case QuizDifficulty.easy:
        return 10;
      case QuizDifficulty.medium:
        return 20;
      case QuizDifficulty.hard:
        return 30;
    }
  }

  List<String> _getCharacterPool() {
    final categories = {
      '字母': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
      '数字': '0123456789'.split(''),
      '标点': ['.', ',', '?', "'", '!', '/', '(', ')', '&', ':', ';', '=', '+', '-', '_', '"', '\$', '@'],
    };

    if (widget.category == '全部') {
      return MorseTranslator.getSupportedCharacters()
          .where((c) => c != ' ')
          .toList();
    }
    
    return categories[widget.category] ?? [];
  }

  void _generateQuestions() {
    final pool = _getCharacterPool();
    if (pool.isEmpty) return;

    _questions = [];
    final usedCharacters = <String>{};

    for (int i = 0; i < _totalQuestions && usedCharacters.length < pool.length; i++) {
      // 随机选择一个未使用的字符
      String correctChar;
      do {
        correctChar = pool[_random.nextInt(pool.length)];
      } while (usedCharacters.contains(correctChar));
      usedCharacters.add(correctChar);

      final morse = MorseTranslator.getCharMorse(correctChar)!;
      
      // 生成错误选项
      final wrongAnswers = <String>[];
      while (wrongAnswers.length < 3) {
        final randomChar = pool[_random.nextInt(pool.length)];
        if (randomChar != correctChar && !wrongAnswers.contains(randomChar)) {
          wrongAnswers.add(randomChar);
        }
      }

      // 混合正确答案和错误答案
      final allAnswers = [correctChar, ...wrongAnswers];
      allAnswers.shuffle(_random);

      _questions.add(QuizQuestion(
        morse: morse,
        correctAnswer: correctChar,
        options: allAnswers,
      ));
    }
  }

  void _selectAnswer(String answer) {
    if (_hasAnswered) return;

    setState(() {
      _selectedAnswer = answer;
      _hasAnswered = true;
      
      if (answer == _questions[_currentQuestionIndex].correctAnswer) {
        _score++;
      }
    });

    // 自动进入下一题或完成测验
    Future.delayed(const Duration(seconds: 1), () {
      if (mounted) {
        _nextQuestion();
      }
    });
  }

  void _nextQuestion() {
    if (_currentQuestionIndex < _questions.length - 1) {
      setState(() {
        _currentQuestionIndex++;
        _hasAnswered = false;
        _selectedAnswer = null;
      });
    } else {
      setState(() {
        _isQuizCompleted = true;
      });
    }
  }

  void _restartQuiz() {
    setState(() {
      _currentQuestionIndex = 0;
      _score = 0;
      _hasAnswered = false;
      _selectedAnswer = null;
      _isQuizCompleted = false;
      _generateQuestions();
    });
  }

  Color _getAnswerColor(String option) {
    if (!_hasAnswered) {
      return Colors.transparent;
    }

    final correctAnswer = _questions[_currentQuestionIndex].correctAnswer;
    
    if (option == correctAnswer) {
      return Colors.green;
    } else if (option == _selectedAnswer) {
      return Colors.red;
    }
    
    return Colors.transparent;
  }

  Widget _buildProgressBar() {
    final progress = (_currentQuestionIndex + 1) / _questions.length;
    
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '第 ${_currentQuestionIndex + 1} / ${_questions.length} 题',
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              Text(
                '得分: $_score',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Theme.of(context).colorScheme.primary,
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 8),
        LinearProgressIndicator(
          value: progress,
          minHeight: 6,
          borderRadius: BorderRadius.circular(3),
        ),
      ],
    );
  }

  Widget _buildQuestionCard() {
    final question = _questions[_currentQuestionIndex];
    
    return Card(
      elevation: 4,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              '这是什么字符？',
              style: Theme.of(context).textTheme.titleMedium,
            ),
            const SizedBox(height: 24),
            Container(
              padding: const EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primaryContainer,
                borderRadius: BorderRadius.circular(16),
              ),
              child: Text(
                question.morse,
                style: TextStyle(
                  fontSize: 48,
                  fontWeight: FontWeight.bold,
                  fontFamily: 'monospace',
                  color: Theme.of(context).colorScheme.onPrimaryContainer,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildOptionsGrid() {
    final question = _questions[_currentQuestionIndex];
    
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: const EdgeInsets.all(16),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
        childAspectRatio: 1.5,
      ),
      itemCount: question.options.length,
      itemBuilder: (context, index) {
        final option = question.options[index];
        final answerColor = _getAnswerColor(option);
        final isSelected = _selectedAnswer == option;
        
        return Card(
          elevation: isSelected ? 8 : 2,
          color: answerColor != Colors.transparent
              ? answerColor.withOpacity(0.2)
              : null,
          child: InkWell(
            onTap: () => _selectAnswer(option),
            borderRadius: BorderRadius.circular(12),
            child: Container(
              decoration: BoxDecoration(
                border: Border.all(
                  color: answerColor != Colors.transparent
                      ? answerColor
                      : Colors.transparent,
                  width: 3,
                ),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Center(
                child: Text(
                  option,
                  style: TextStyle(
                    fontSize: 36,
                    fontWeight: FontWeight.bold,
                    color: answerColor != Colors.transparent
                        ? answerColor
                        : null,
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildResultScreen() {
    final percentage = (_score / _questions.length * 100).round();
    String message;
    IconData icon;
    Color color;

    if (percentage >= 90) {
      message = '太棒了！你是摩尔斯电码大师！';
      icon = Icons.emoji_events;
      color = Colors.amber;
    } else if (percentage >= 70) {
      message = '做得很好！继续努力！';
      icon = Icons.thumb_up;
      color = Colors.green;
    } else if (percentage >= 50) {
      message = '不错的开始，多加练习会更好！';
      icon = Icons.trending_up;
      color = Colors.blue;
    } else {
      message = '继续学习，你会进步的！';
      icon = Icons.school;
      color = Colors.orange;
    }

    return Center(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, size: 120, color: color),
            const SizedBox(height: 24),
            Text(
              message,
              style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 32),
            Card(
              child: Padding(
                padding: const EdgeInsets.all(24),
                child: Column(
                  children: [
                    Text(
                      '测验结果',
                      style: Theme.of(context).textTheme.titleLarge?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 16),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        _buildStatItem('正确', _score.toString(), Colors.green),
                        _buildStatItem(
                          '错误',
                          (_questions.length - _score).toString(),
                          Colors.red,
                        ),
                        _buildStatItem('准确率', '$percentage%', Colors.blue),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 32),
            Row(
              children: [
                Expanded(
                  child: FilledButton.icon(
                    onPressed: _restartQuiz,
                    icon: const Icon(Icons.refresh),
                    label: const Text('再测一次'),
                    style: FilledButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () => Navigator.pop(context),
                    icon: const Icon(Icons.home),
                    label: const Text('返回'),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatItem(String label, String value, Color color) {
    return Column(
      children: [
        Text(
          value,
          style: TextStyle(
            fontSize: 32,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        Text(
          label,
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_questions.isEmpty) {
      return Scaffold(
        appBar: AppBar(title: const Text('测验')),
        body: const Center(child: Text('无法生成测验题目')),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(
          '${widget.category}测验',
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        actions: [
          if (!_isQuizCompleted)
            IconButton(
              icon: const Icon(Icons.close),
              onPressed: () {
                showDialog(
                  context: context,
                  builder: (context) => AlertDialog(
                    title: const Text('确定要退出吗？'),
                    content: const Text('当前的测验进度将会丢失。'),
                    actions: [
                      TextButton(
                        onPressed: () => Navigator.pop(context),
                        child: const Text('取消'),
                      ),
                      TextButton(
                        onPressed: () {
                          Navigator.pop(context);
                          Navigator.pop(context);
                        },
                        child: const Text('确定'),
                      ),
                    ],
                  ),
                );
              },
            ),
        ],
      ),
      body: _isQuizCompleted
          ? _buildResultScreen()
          : Column(
              children: [
                const SizedBox(height: 16),
                _buildProgressBar(),
                const SizedBox(height: 24),
                _buildQuestionCard(),
                const SizedBox(height: 16),
                Expanded(child: _buildOptionsGrid()),
              ],
            ),
    );
  }
}

/// 测验问题类
class QuizQuestion {
  final String morse;
  final String correctAnswer;
  final List<String> options;

  QuizQuestion({
    required this.morse,
    required this.correctAnswer,
    required this.options,
  });
}

